<template>
    <div class="newAdmin">
        <h1 style="margin-bottom:20px;">{{$route.params.id?'编辑':'新建'}}管理员</h1>
        <el-form :model="user" label-width="120px" ref="ruleFormRef" :rules="rules">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="user.username" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="user.password" type="password" ref="pwdRef"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveUserInfo" class="btn">登录</el-button>
          </el-form-item>
        </el-form>
    </div>
</template>

<script>
import {reqAdminAdd,reqAdminSearchById,reqAdminModify} from '../../../api/index';
import { ElMessage } from 'element-plus';
export default {
    name:'NewAdmin',
    data(){
      return {
        user:{
          username:'',
          password:''
        },
        rules:{
          password:[
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 3, max: 15, message: '密码长度必须为3-15位', trigger: 'blur' },
          ]
        }
      }
    },
    methods:{
      async saveUserInfo(){
        if(this.user.password == ''){
          this.$refs.pwdRef.focus();
          return;
        }
        //判断是添加还是修改管理员
        if(!this.$route.params.id){
          let res = await reqAdminAdd(this.user.username,this.user.password);
          ElMessage({
            message: '添加成功',
            type: 'success',
          });
        }else{
          let res = await reqAdminModify(this.$route.params.id,this.user.username,this.user.password);
          ElMessage({
            message: '修改成功',
            type: 'success',
          });
        }
        //切换至管理员列表
        this.$router.push('/adminlist');
      },
      async getAdminById(){
        let res = await reqAdminSearchById(this.$route.params.id);
        this.user.username = res.name;
      }
    },
    mounted(){
      if(this.$route.params.id){
        this.getAdminById();
      }
    }
}
</script>

<style scoped>
  .newAdmin{
    padding:20px;
  }
</style>